/*
 * dateAnalysis.js
 * 时序分析
 */
;
(function (call) {
    var main = {
        baseUrl: CafeJS.CXT,
        datepicker: null,
        elementArr: [
			{ "name": "2m温度", "elementId": "t2m", "color": "#fe5150", "forecastId": "tmp" },
			{ "name": "风", "elementId": "wind", "color": "#1ca1e2", "forecastId": "eda" },
			{ "name": "10m风", "elementId": "gust10m", "color": "#595fd6", "forecastId": "tmp" }, 
			{ "name": "相对湿度", "elementId": "rh2m", "color": "#00d4bb", "forecastId": "rh" }
		],
        currentTime: "",
        elementIds: [],
        elementForecastIds: [],
        elementHeights: [],
        colors: [],
        elementNames: [],
        endTime: "",
        startTime: "",
        echartOption: {},
        echartObj: Object,
        stationKey: '',
        isByDateLength: false,
        router: {
			getSiterData: '/zhfx/station/queryHourYbStation',
			getChartData:'/stnData/querySTNFromSignEleAndMultSta',
		},
        init: function () {
            var that = this;
            that.currentTime = window.stnfanalysis.currentTime;
            that.initDatePicker(1, 'yyyy-MM-dd hh', 'H', []);
            that.echartOption = that.getEchartOption();
            that.initView();
        },
		getEchartOption:function(){
            var that = this;
            return {
                title: {
                    text: '',
                    x: 'center',
                    top: 20
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    },
                    showTitle: false,
                    color: "#045DF8",
                    top: 20,
                    right: 30
                },
                tooltip: {
                    trigger: "axis",
                    textStyle: {
                        fontSize: 13
                    },
                    formatter: function (params) {
                        return that.setEchartShow(params);
                    },
                    padding: 8
                },
                xAxis: {
                    type: "category",
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        interval:0,
                        textStyle: { //改变刻度字体样式
                            color: function (value, index) {
                                if ($(".dateType .active").attr("name") === "10") {
                                    value = value + ":00";
                                    return that.getTimeBtDate(value, "10",index).color;
                                } else if ($(".dateType .active").attr("name") === "60") {
                                    value = value + ":00:00";
                                    return that.getTimeBtDate(value, "60",index).color;
                                }
                            },
                            fontSize: 12
                        },
                        formatter: function (value, index) {
                            if ($(".dateType .active").attr("name") === "10") {
                                value = value + ":00";
                                return that.getTimeBtDate(value, "10",index).time;
                            } else if ($(".dateType .active").attr("name") === "60") {
                                value = value + ":00:00";
                                return that.getTimeBtDate(value, "60",index).time;
                            }
                        }
                    },
                    data: []
                },
				dataZoom: [
					{
						show: true,
						realtime: true,
						start: 50,
						end: 100,
						bottom: 20,
						left:'10%',
						right:'10%'
					},
					{
						type: 'inside',
						realtime: true,
						start: 0,
						end: 50
					}
                ],
                legend: {
                    show: true,
                    icon: "roundRect",
                    itemWidth: 20,
                    itemHeight: 10,
                    itemGap: 15,
                    top: 55,
                    right: 20,
                    data: [],
                    textStyle: {
                        color: "#333333",
                        fontSize: 14
                    }
                },
                grid: {
                    show: true,
                    bottom: "12%",
                    top: "18%",
                    containLabel: true,
                    borderWidth: 0
                },
                yAxis: [],
                series: []
            }
        },
		
		initView: function () {
            var that = this;
            that.echartObj = echarts.init(document.getElementById("analysisEchart"));
            that.echartObj.clear();
			that.setElements();
            that.getSiteData();
        },
        // 初始化时间控件
        initDatePicker: function (timeInterval, dateFmt, dateType, customHm) {
            var that = this;
            that.datepicker = CafeJS.Datepicker({
                appendTo: "#datepicker-dateAnalysis",
                type: 3,
                curDate: that.currentTime,
                dateFmt: dateFmt,
                dateType: dateType,
                timeInterval: timeInterval,
                customHm: customHm,
                call: function (val) {
                    that.getData(false);
                }
            });
        },
		//获取常规站点集合
        getSiteData: function () {
            var that = this;
            var parentObj = $(".sites");
            parentObj.html("");
			
			let siteDatas = [
				{stationId:'54517',stationName:'天津'},
				{stationId:'54527',stationName:'西青'},
				{stationId:'54622',stationName:'津南'},
				{stationId:'54623',stationName:'塘沽'},
				{stationId:'A2967',stationName:'东丽无瑕街苏庄子'},
				{stationId:'A3169',stationName:'滨海新区泰达街'},
				{stationId:'A3364',stationName:'津南农业园区'},
				{stationId:'A3507',stationName:'津南会展中心气象观测站'},
				{stationId:'A3590',stationName:'全运村特种站'}
			]
            for (var i = 0; i < siteDatas.length; i++) {
				var obj = $("<div class='analysisBtn' name='" + siteDatas[i].stationId + "'>" + siteDatas[i].stationName + "</div>");
				parentObj.append(obj);
				obj.unbind("click").bind("click", function () {
					$(this).addClass("active").siblings().removeClass("active");
					that.getData(false);
				});
			}
			var stationId = window.stnfanalysis.stationId;
			if (stationId) {
				$(".sites .analysisBtn[name=" + stationId + "]").addClass("active").siblings().removeClass("active");
			}
			if(!window.stnfanalysis.stationLon){
			   $(".sites .analysisBtn").eq(1).addClass("active").siblings().removeClass("active");
			}
			that.bindEvt();
        },
		//根据时间，获取元素选择
        setElements: function () {
            //点击要素选择
            var that = this;
            var elementsObj = $(".elements");
            elementsObj.html("");
            var data = that.elementArr;
            for (var i = 0; i < data.length; i++) {
                obj1 = $("<div class='analysisBtn' name='" + data[i].elementId + "' color='" + data[i].color + "' forecastId='" + data[i].forecastId + "'>" + data[i].name + "</div>");
                obj1.data("ele", data[i]);
                obj1.addClass("element");
                elementsObj.append(obj1);
                if (i === 0) {
                    obj1.addClass("active");
                }
                obj1.unbind("click").bind("click", function () {
					if (!$(this).hasClass("active")) {
                        $(this).addClass("active").siblings().removeClass("active");
						that.getData(false);
                    }
                })
            }
        },
		//初始化数据源
        bindEvt: function () {
            var that = this;
            //时间间隔切换
            $(".dateType >div").each(function () {
                $(this).unbind("click").bind("click", function () {
					if ($(this).hasClass('active')) return;
                    $(this).addClass("active").siblings().removeClass("active");
                    that.getData(false);
                    
                })
            })
			that.getData();
        },
        //点击数据源，获取数据
        getData: function () {
			debugger
            var that = this;
            var currentTime = that.datepicker.getVal();     //这个时间点为当前时间，分隔时间点
			var queryTime = new Date(currentTime+":00").format("yyyyMMddhh");
            var url = that.router.getChartData+"?foreTime="+queryTime+"&stationIds="+$(".sites .active").attr("name")+"&element="+$(".elements .active").attr("name");
			console.log(url);
			$.ajax(url, {
				method: "POST",
				contentType: "application/json",
				dataType: "json",
				success: function (res) {
					that.echartObj.clear();
					if(res[0] && res[0].length>0){
						that.drawEchart(res[0]);
					}
				},
				error:function(){
					that.echartObj.clear();
				}
			})
        },

        /********设置echart**********/
        drawEchart: function (resdata) {
            var that = this;
			console.dir(resdata);
            that.echartOption = that.getEchartOption();
			that.echartOption.color = ['#ff0000','#00ff00','#0000ff'];
			var currentTime = that.datepicker.getVal();     //这个时间点为当前时间，分隔时间点
			var queryTime = new Date(currentTime+":00").format("yyyy年MM月dd日hh时");
			
			that.echartOption.title.text = queryTime+$(".sites .active").text()+$(".elements .active").text()+"时序图";
			var dataArr = [];
			var xData = [];
			var currentTime = that.datepicker.getVal(); 
			var newSeries = [];
			var seriesData = [];
			var calcData = [];
			var allTime = []
			resdata.map(item=>{
				if($(".elements .active").attr("forecastId") == "eda"){
					seriesData.push({
						value:item.value1?Number(item.value1):null,
						valueWd:item.value2?Number(item.value2):null
					});
				}else{
					seriesData.push(item.value1?Number(item.value1):null);
				}
				
				calcData.push(item.value1?Number(item.value1):null);
				allTime.push(new Date(new Date(currentTime+":00").getTime()+item.aging*60*60*1000).format("yyyy-MM-dd hh:mm"))
			})
			var min = that.getMinInArr(calcData).toFixed(0);
            var max = that.getMaxInArr(calcData).toFixed(0);
			var yAxis = that.getYAxisObj();
			yAxis["name"] = $(".elements .active").text();
			yAxis["min"] = min;
			yAxis["max"] = max;
			yAxis["interval"] = (max - min) / 10;
			let seriesObj = {
				connectNulls:true,
				data:seriesData,
				type: "line",
				name:$(".elements .active").text(),
				showAllSymbol: true,
				smooth: true,
				symbol: "circle",
				symbolSize: 5
			}
			if($(".elements .active").attr("forecastId") == "eda"){
				seriesObj = that.setSerieSymbol(seriesObj);
			}
			newSeries.push(seriesObj)
			that.echartOption.series = newSeries;
            that.echartOption.yAxis = [yAxis];
            that.echartOption.xAxis.data = allTime;
			that.echartObj.clear();
            that.echartObj.setOption(that.echartOption, true);
        },

        //获取最大值
        getMaxInArr: function (arr) {
            //arr = arr.filter(val => val > 0);
            return Math.max.apply(null, arr) + 1;
        },
        //获取最小值
        getMinInArr: function (arr) {
            //arr = arr.filter(val => val > 0);
            var min = Math.min.apply(null, arr);
            if (min !== 0) {
                min = min - 1;
            }
            return min;
        },
		
		//获取y轴对象
        getYAxisObj: function () {
            return {
                type: "value",
                axisLabel: {
                    formatter: "{value}",
                    textStyle: {
                        //改变刻度字体样式
                        color: "#333333",
                        fontSize: 12
                    }
                },
                splitNumber: 10,
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "#333333"
                    }
                }
            };
        },
		//定义鼠标移到echart中弹框的内容
        setEchartShow: function (params) {
            var that = this;
            var htmlStr = "";
            var xName = params[0].name;
            htmlStr = htmlStr + xName + '<br/>';
            var unit = "";
            for (var i = 0; i < params.length; i++) {
                var seriesName = params[i].seriesName;
                var color = params[i].color;
                var value = params[i].value;
                var wdValue = "";
                if (seriesName.indexOf("风") > -1) {
                    value = params[i].data.value;
                    wdValue = params[i].data.valueWd; // 定义风向
                    if (value === "null" || typeof value === "undefined" || value === null) {
                        value = "-"
                    } else {
                        value = Number(value).toFixed(1);
                        wdValue = WindUtil.getWindDire(WindUtil.calcWindDire(wdValue)).CH;
                        value = wdValue + " " + value;
                    }
                }else{
                    if (value === "null" || typeof value === "undefined") {
                        value = "-";
                    }else{
                        value = Number(value).toFixed(1);
                    }
                }
                
                htmlStr = htmlStr + '<div style="display: flex;align-items: center"><div style="background-color: ' + color + ';height: 10px;width: 10px;border-radius: 50%;margin-right: 6px"></div>';
                var elementName = $(".elements .active").text();
				unit = that.getUnitbyElement(elementName);
				htmlStr = htmlStr + seriesName + '：' + value + unit + "<br/></div>";
            }
            return htmlStr;
        },
        getUnitbyElement: function (name) {
            var unit = "";
            switch (name) {
                case "2m温度":
                    unit = "℃";
                    break;
                case "降水量":
                    unit = "mm";
                    break;
                case "相对湿度":
                    unit = "%";
                    break;
                case "10m风":
                case "风":
                    unit = "m/s";
                    break;
                case "海平面气压":
                    unit = "hPa";
                    break;
                case "总云量":
                    unit = "%";
                    break;
                case "能见度":
                    unit = "m";
                    break;
            }
            return unit
        },
        
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		




        //如果是风，节点信息为风向图标
        setSerieSymbol: function (serieObj) {
            serieObj.symbolSize = 18;
            serieObj.symbol = function (obj, param) {
                if (!param.data)
                    return "";
                var windD = param.data.valueWd;
                if ((windD !== 0 && !windD) || windD > 360)
                    return "";
                var en = WindUtil.getWindDire(WindUtil.calcWindDire(windD)).EN;
                return "image:///business/common/css/images/wind/" + en + ".png";
            }
            return serieObj;
        },

        //获取时间，根据时间类型，获取时，分，秒
        getTimeBtDate: function (dateStr, flag, index) {
            var mounth = new Date(dateStr).getMonth() + 1;
            var day = new Date(dateStr).getDate();
            var hour = new Date(dateStr).getHours();
            var minutes = new Date(dateStr).getMinutes();
            day = day > 9 ? day + "" : "0" + day;
            hour = hour > 9 ? hour + "" : "0" + hour;
            minutes = minutes > 9 ? minutes + "" : "0" + minutes;
            mounth = mounth > 9 ? mounth + "" : "0" + mounth;
            var returnObj = { "time": "", "color": "#333333" };
            if (flag === "10") {
                if (hour + minutes === "0000" || index == 0) {
                    returnObj.color = "#FEA444";
                    returnObj.time = hour + ":" + minutes + "\n" + day;
                } else {
                    returnObj.time = hour + ":" + minutes
                }
            } else if (flag === "60") {
                if(index == 0  || (this.isByDateLength && (hour == "08" || hour == "20"))){
                    returnObj.color = "#FEA444";
                    returnObj.time = day + "/" + hour; 
                }else{      
                    var xAxisArr = this.echartOption.xAxis.data;
                    var perTime = xAxisArr[index-1]+":00:00";
                    var currTime = xAxisArr[index]+":00:00";
                    if(new Date(perTime).getDate() != new Date(currTime).getDate()){
                        returnObj.color = "#FEA444";
                        returnObj.time = day + "/" + hour;
                    }else{
                        returnObj.time = hour;
                    }
                }
            }
            return returnObj;
        },        
    };
    if (typeof call === 'function') {
        CafeJS.stnfdateAnalysis = main;
        call(main);
    }

})(function (main) {
    CafeJS.models(['datepicker', 'legentconfig','timeLine3'], function () {
        main.init();
    });
});
